import { ref } from 'vue';

/**
 * 树形结构构建 hook
 * @returns 返回树形结构相关方法和状态
 */
export function useTreeBuilder() {
  const treeData = ref([]);

  /**
   * 构建树形结构
   * @param data 原始数据数组
   * @param idKey ID字段名称，默认为'accessGroupId'
   * @param parentKey 父ID字段名称，默认为'parentGroupId'
   * @param childrenKey 子节点字段名称，默认为'children'
   * @returns 构建好的树形结构
   */
  const buildTree = (
    data: any[], 
    idKey: string = 'accessGroupId', 
    parentKey: string = 'parentGroupId', 
    childrenKey: string = 'children'
  ) => {
    const map = new Map();
    const tree :any= [];

    // 创建映射表并初始化children
    data.forEach(item => {
      map.set(item[idKey], { ...item, [childrenKey]: [] });
    });

    // 构建树结构
    data.forEach(item => {
      const node = map.get(item[idKey]);
      if (item[parentKey] === 0 || item[parentKey] === null) {
        tree.push(node);
      } else {
        const parent = map.get(item[parentKey]);
        if (parent) {
          parent[childrenKey].push(node);
        } else {
          tree.push(node);
        }
      }
    });

    treeData.value = tree;
    return tree;
  };

  return {
    treeData,
    buildTree
  };
}